#include "LMButton.h"


const int K_MARGIN = 5;
const int K_MIN_WIDTH = 100;
const int K_BORDER = 2;

LMButton::LMButton(std::string t, sf::Vector2f p, sf::Font* f)
{
	colour = sf::Color::White;
	position = p;
	font = f;
	text = sf::Text(t, *font);

	text.setFont(*font);
	text.setCharacterSize(20);
	text.setColor(colour);

	pressed = false;
	
	resize();
}




LMButton::~LMButton(void)
{
}



void LMButton::setText(std::string str)
{
	//text = str;
}

sf::Text LMButton::getText()
{
	return text;
}

sf::RectangleShape LMButton::getBox()
{
	return box;
}

void LMButton::setPosition(sf::Vector2f p)
{
	position = p;
	resize();
}

sf::Vector2f LMButton::getPosition()
{
	return position;
}

bool LMButton::checkClicked(sf::Vector2f mouse)
{
	sf::FloatRect bounds = box.getGlobalBounds();
	if (mouse.x <= bounds.left+bounds.width) {
		if (mouse.x >= bounds.left) {
			if (mouse.y <= bounds.top+bounds.height) {
				if (mouse.y >= bounds.top) {
					box.setFillColor(sf::Color::White);
					text.setColor(sf::Color::Black);
					pressed = true;
				}
			}
		}
	}
	return pressed;
}

bool LMButton::checkClicked(sf::Vector2i mouse)
{
	sf::Vector2f floatMouse(mouse.x, mouse.y);
	return checkClicked(floatMouse);
}

bool LMButton::isClicked()
{
	return pressed;
}


void LMButton::releaseClicked()
{
	pressed = false;
	box.setFillColor(sf::Color::Transparent);
	text.setColor(sf::Color::White);
	resize();
}

void LMButton::resize()
{
	sf::FloatRect textRect = text.getLocalBounds();

	if (textRect.width+(2*K_MARGIN) > K_MIN_WIDTH) {
		box.setSize(sf::Vector2f(textRect.width+(2*K_MARGIN), textRect.height+(2*K_MARGIN)));
		text.setPosition(position.x+K_MARGIN, position.y+K_MARGIN);
	}
	else {
		box.setSize(sf::Vector2f(K_MIN_WIDTH, textRect.height+(2*K_MARGIN)));
		text.setPosition(position.x + (K_MIN_WIDTH-textRect.width-K_MARGIN*2)/2 + K_MARGIN, position.y+K_MARGIN);
	}

	box.setPosition(position.x, position.y+textRect.height/2 - K_MARGIN);

	box.setFillColor(sf::Color::Transparent);
	box.setOutlineColor(colour);
	box.setOutlineThickness(K_BORDER);
}



void LMButton::drawThis(WindowManager* w)
{
	w->draw(getBox());
	w->draw(getText());
}